package group.rober.jeki.controller.admin;

import group.rober.jeki.entity.Tag;
import group.rober.jeki.service.ArticleService;
import group.rober.jeki.service.TagService;
import group.rober.runtime.kit.NumberKit;
import group.rober.runtime.kit.StringKit;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;
import java.util.Map;

@Api(description = "后台管理-标签")
@Controller
@RequestMapping("/admin")
public class AdminTagController {
    @Autowired
    TagService tagService;
    @Autowired
    ArticleService articleService;

    @RequestMapping("/tag-list")
    ModelAndView tagList() {
        Map<String, Object> vars = new HashMap<String, Object>();
        vars.put("tagList",tagService.getTagList());
        vars.put("tag",new Tag());
        return new ModelAndView("views/admin/tag-list", vars);
    }

//    @RequestMapping("/tag-create")
//    ModelAndView tagCreate() {
//        Tag tag = new Tag();
//        return new ModelAndView("views/admin/tag-editor", ["tag": tag]);
//    }

    @RequestMapping("/tag/{tagId}")
    ModelAndView tagEditor(@PathVariable("tagId") String tagId) {
        Tag tag = tagService.getTag(tagId);
        Map<String, Object> vars = new HashMap<String, Object>();
        vars.put("tag",tag);
        return new ModelAndView("views/admin/tag-editor", vars);
    }

    @RequestMapping("/tag/delete-action/{tagId}")
    ModelAndView tagDelete(@PathVariable("tagId") String tagId) {
        Tag tag = tagService.getTag(tagId);
        tagService.deleteTag(tag);
        return new ModelAndView("redirect:/admin/tag-list");
    }

    @RequestMapping(path = "/tag/save-action", method = RequestMethod.POST)
    ModelAndView tagSaveAction(@ModelAttribute Tag tag) {
        if (StringKit.isBlank(tag.getId())) {
            tag.setId(NumberKit.nanoTime36());
        }
        if(StringKit.isBlank(tag.getCode())){
            tag.setCode(tag.getName());
        }
        tagService.saveTag(tag);
        return new ModelAndView("redirect:/admin/tag-list");
    }
    @RequestMapping(path = "/tag/statistics-action", method = RequestMethod.GET)
    ModelAndView statisticsTagAction() {
        articleService.statisticsArticleTag();
        return new ModelAndView("redirect:/admin/tag-list");
    }
}
